package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static String url="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
   private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {

        String openid = getOpenId(userLoginDTO);
        //如果openid为null说明登录失败 抛异常
       if (openid==null){
           throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
       }

        //不是异常就根据openid查询user表 来判断是否是新用户
       User user=userMapper.findByid(openid);

        //如果为空就插入数据
       if (user==null){
        user= User.builder()
                   .openid(openid)
                   .createTime(LocalDateTime.now())
                   .build();
           userMapper.insert(user);
       }
        //返回数据
     return user;
    }

    public String getOpenId(UserLoginDTO userLoginDTO){
        //调用微信接口 获取openid
        Map<String, String> paramMap=new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(url, paramMap);

        //解析json对象获取openid
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
